/****************************************************
          File Name:48-1-reader.c
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Tue 16 Sep 2014 07:48:59 PM CST
*****************************************************/

#include"svshm_xfr.h"

int main(int argc,char *argv[])
{
    int shmid, xfrs, bytes;
    struct shmseg *shmp;

    shmid=shmget(SHM_KEY,0,0);
    if(shmid==-1)
        err("shmget");

    shmp=shmat(shmid,NULL,0); // if RDONLY, would receive SIGSEGV
    if(shmp==(void *)-1)
        err("shmat");

    for(xfrs=0, bytes=0;;xfrs++)
    {
        if(shmp->status==false)
        {
			bytes+=shmp->cnt;
            shmp->cnt=write(STDOUT_FILENO,shmp->buf,BUF_SIZE);
            if(shmp->cnt==-1)
                err("write");
	        shmp->status=true;
        }

        if(shmp->exit==true)
            break;

		sleep(1);
    }

    fprintf(stderr,"Received %d bytes (%d xfrs)\n", bytes, xfrs);
    exit(EXIT_SUCCESS);
}
